<?php

namespace app\admin\controller;


use app\admin\model\SystemAdmin;
use app\admin\model\SystemQuick;
use app\common\controller\AdminController;
use think\App;
use think\facade\Db;
use think\facade\Env;

class Index extends AdminController
{

    /**
     * 后台主页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        $url='#';
        switch (session('admin')['type']){
            //case 3:$url='township.docx';break;
            //case 4:$url='village.docx';break;
        }
        return $this->fetch('', [
            'admin' => session('admin'),
            'url'=>$url
        ]);
    }

    /**
     * 后台欢迎页
     * @return string
     * @throws \Exception
     */
    public function welcome()
    {
        //快捷菜单
        $quicks = SystemQuick::field('id,title,icon,href')
            ->where(['status' => 1])
            ->order('sort', 'desc')
            ->limit(8)
            ->select();
        $this->assign('quicks', $quicks);
        $newCountArr = [
            //待办 办理中 完成 超时
            'deal'=>0,'dealing'=>0,'finish'=>0,'outtime'=>0,
            'wait'=>0,
            'visit_total'=>0,'visit_num'=>0,
            'hnzj_count'=>0,'xwql_count'=>0,'gsgk_count'=>0,'mes_count'=>0
        ];
        $messageArr=[
            'total'=>0,'wai'=>0,'nei'=>0
        ];
        //办事统计
        $userType = $this->admin['type'];
        $areaId = $this->admin['area_id'];
        /*if ($userType == 3||$userType==6){
            $newCountArr['wait']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and (a.status = 3) and b.is_township = 2')->count();
            $newCountArr['deal']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and (a.status = 4) and b.is_township = 2')->count();
            $newCountArr['finish']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and (a.status = 5 or a.status = 6 or a.status = 7 or a.status = -2 or a.status = -3) and b.is_township = 2')->count();
            $newCountArr['outtime']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and a.is_township_overtime = 2 and b.is_township = 2')->count();
            $newCountArr['visit_total']=Db::table('ea_xwql_visits')->removeOption('where')->where(['township'=>$areaId])->count();
            $newCountArr['visit_num']=Db::table('ea_wx_user')->removeOption('where')->where(['status'=>1])->where(['township'=>$areaId])->count();
            $newCountArr['hnzj_count']=Db::table('ea_xwql_hnzj')->removeOption('where')->where(['township'=>$areaId])->count();
            $newCountArr['xwql_count']=Db::table('ea_xwql_xwql')->removeOption('where')->where(['township'=>$areaId])->count();
            $newCountArr['gsgk_count']=Db::table('ea_xwql_publicity')->removeOption('where')->where(['township'=>$areaId])->count();
            $newCountArr['mes_count']=Db::table('ea_consult_message')->removeOption('where')->where(['township'=>$areaId])->count();
        }else if($userType == 4){
            $newCountArr['wait']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and (a.status = 1) and b.is_village = 2')->count();
            $newCountArr['deal']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and (a.status = 2) and b.is_village = 2')->count();
            $newCountArr['finish']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and (a.status = 3 or a.status = 4 or a.status = 5 or a.status = 6 or a.status = 7 or a.status = -1 or a.status = -2 or a.status = -3) and b.is_village = 2')->count();
            $newCountArr['outtime']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and a.is_village_overtime = 2 and b.is_village = 2')->count();
        }else if($userType==5){
            $messageArr['total']=Db::table('ea_consult_message')->removeOption('where')->count();
            $messageArr['wai']=Db::table('ea_consult_message')->removeOption('where')->where(['is_xiansuo'=>1])->count();
            $messageArr['nei']=Db::table('ea_consult_message')->removeOption('where')->where(['is_xiansuo'=>2])->count();
        }else if($userType==2){
            $department=$this->admin['department'];
            $newCountArr['wait']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.department_id = '.$department.' and (a.status = 5) and b.is_department = 2')->count();
            $newCountArr['deal']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.department_id = '.$department.' and (a.status = 6) and b.is_department = 2')->count();
            $newCountArr['finish']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.department_id = '.$department.' and (a.status = 5 or a.status = 6 or a.status = 7 or a.status = -3) and b.is_department = 2')->count();
            $newCountArr['outtime']=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.department_id = '.$department.' and a.is_department_overtime = 2 and b.is_department = 2')->count();
            $newCountArr['reviewTotal']=Db::table('ea_xwql_hnzj')->removeOption('where')->where([['department','=',$department],['status','in',[3,4,5]]])->count();
            $newCountArr['reviewWait']=Db::table('ea_xwql_hnzj')->removeOption('where')->where([['department','=',$department],['status','=',3]])->count();
            $newCountArr['reviewed']=Db::table('ea_xwql_hnzj')->removeOption('where')->where([['department','=',$department],['status','in',[4,5]]])->count();
            $newCountArr['reviewAdopt']=Db::table('ea_xwql_hnzj')->removeOption('where')->where([['department','=',$department],['status','=',4]])->count();
            $newCountArr['reviewFailed']=Db::table('ea_xwql_hnzj')->removeOption('where')->where([['department','=',$department],['status','=',5]])->count();
        }*/
        $this->assign('userType', $userType);
        $this->assign('countArr', $newCountArr);
        $this->assign('messageArr', $messageArr);
		$this->assign('area_id', $areaId);
        return $this->fetch();
    }

    public function statisticApi(){
        $return = [];
        $return['code'] = 0;
        $return['msg'] = '暂无数据';
        $return['list'] = [];
        $return['xarr'] = [];
        $return['legend'] = [];

        //近半年
        $today = date("Y-m-d");
        $xArr = array();
        $old_time = strtotime('-6 month',strtotime($today));
        for($i = 1;$i <= 6; ++$i){
            $t = strtotime("+$i month",$old_time);
            $xArr[]=date('m',$t).'月';
        }
        //列表
//办事统计
        $userType = $this->admin['type'];
        $areaId = $this->admin['area_id'];
        if ($userType == 3||$userType==6){
            $waitList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and (a.status = 3) and b.is_township = 2')->field('a.*')->select();
            $dealList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and (a.status = 4) and b.is_township = 2')->field('a.*')->select();
            $finishList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and (a.status = 4 or a.status = 6 or a.status = 7 or a.status = 8) and b.is_township = 2')->field('a.*')->select();
            $outtimeList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.township = '.$areaId.' and a.is_township_overtime = 2 and b.is_township = 2')->field('a.*')->select();
        }else if($userType == 4){
            $waitList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and (a.status = 1) and b.is_village = 2')->field('a.*')->select();
            $dealList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and (a.status = 2) and b.is_village = 2')->field('a.*')->select();
            $finishList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and (a.status = 3 or a.status = 4 or a.status = 5 or a.status = 6 or a.status = 7 or a.status = -1 or a.status = -2 or a.status = -3) and b.is_village = 2')->field('a.*')->select();
            $outtimeList=Db::table('ea_consult_work')->alias('a')->leftjoin('xwql_work b', 'a.work_id = b.id')->removeOption('where')->where('a.village = '.$areaId.' and a.is_village_overtime = 2 and b.is_village = 2')->field('a.*')->select();
        }
        $workArr = [
            '待办理'=>['name'=>'待办理','type'=>'line','arr'=>[]],
            '办理中'=>['name'=>'办理中','type'=>'line','arr'=>[]],
            '已完成'=>['name'=>'已完成','type'=>'line','arr'=>[]],
            '已超时'=>['name'=>'已超时','type'=>'line','arr'=>[]],
        ];
        if (count($waitList)>0){
            $waitList = $waitList->toArray();
            foreach ($waitList as $k=>$v){
                $waitList[$k]['month'] = date('m',$v['create_time']).'月';
                $waitList[$k]['name'] = '待办理';
            }
            foreach ($waitList as $k=>$v){
                $workArr[$v['name']]['arr'][$v['month']][] = $v['name'];
            }
        }
        if (count($dealList)>0){
            $dealList = $dealList->toArray();
            foreach ($dealList as $k=>$v){
                $dealList[$k]['month'] = date('m',$v['create_time']).'月';
                $dealList[$k]['name'] = '办理中';
            }
            foreach ($dealList as $k=>$v){
                $workArr[$v['name']]['arr'][$v['month']][] = $v['name'];
            }
        }
        if (count($finishList)>0){
            $finishList = $finishList->toArray();
            foreach ($finishList as $k=>$v){
                $finishList[$k]['month'] = date('m',$v['create_time']).'月';
                $finishList[$k]['name'] = '已完成';
            }
            foreach ($finishList as $k=>$v){
                $workArr[$v['name']]['arr'][$v['month']][] = $v['name'];
            }
        }
        if (count($outtimeList)>0){
            $outtimeList = $outtimeList->toArray();
            foreach ($outtimeList as $k=>$v){
                $outtimeList[$k]['month'] = date('m',$v['create_time']).'月';
                $outtimeList[$k]['name'] = '已超时';
            }
            foreach ($outtimeList as $k=>$v){
                $workArr[$v['name']]['arr'][$v['month']][] = $v['name'];
            }
        }
        $workArr = array_values($workArr);
        foreach ($workArr as $k=>$v){
            $workArr[$k]['data'][$xArr[0]] = 0;
            $workArr[$k]['data'][$xArr[1]] = 0;
            $workArr[$k]['data'][$xArr[2]] = 0;
            $workArr[$k]['data'][$xArr[3]] = 0;
            $workArr[$k]['data'][$xArr[4]] = 0;
            $workArr[$k]['data'][$xArr[5]] = 0;
            foreach ($v['arr'] as $key=>$val){
                $workArr[$k]['data'][$key] = count($val);
                unset($workArr[$k]['arr']);
            }
        }
        foreach ($workArr as $k=>$v){
            $workArr[$k]['data'] = array_values($v['data']);
        }

        /*$workArr = [
            ['name'=>'待办理','type'=>'line','data'=>[0,0,0,0,0,0]],
            ['name'=>'办理中','type'=>'line','data'=>[0,0,0,0,0,0]],
            ['name'=>'已完成','type'=>'line','data'=>[0,0,0,0,0,0]],
            ['name'=>'已超时','type'=>'line','data'=>[0,0,0,0,0,0]],
        ];*/

        $return['legend'] = ['待办理', '办理中', '已完成', '已超时'];
        $return['xarr'] = $xArr;
        $return['code'] = 1;
        $return['msg'] = '操作成功';
        $return['list'] = array_values($workArr);
        return json($return);
    }

    /**
     * 修改管理员信息
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editAdmin()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row
                    ->allowField(['head_img', 'phone', 'remark', 'update_time'])
                    ->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 修改密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPassword()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            // 判断是否为演示站点
            $example = Env::get('easyadmin.example', 0);
            $example == 1 && $this->error('演示站点不允许修改密码');
            if(preg_match('/((^[0-9]{6,})|(^[a-z]{6,})|(^[A-Z]{6,}))$/',$post['password'])){
                $this->error('检测到弱密码，请重新填写密码！');
            }
            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
}
